
const jwt = require("jsonwebtoken");
const { SECRET_KEY } = require("../config/index.js");
const utils = require("./index.js");
const log4js = require('./log4j.js')

const checkToken = async (ctx, next) => {
    const url = ctx.request.url;

    if (url == "/api/user/login" || url == '/api/upload') {
        await next();
    } else {
        const token = ctx.request.header.authorization ? JSON.parse(ctx.request.header.authorization) : '';
        try {
            if (token) {
                jwt.verify(token, SECRET_KEY);
                await next();
            } else {
                ctx.body = utils.fail('', utils.CODE.AUTH_ERROR)
            }
        } catch (error) {
            log4js.error(`${error.stack}`)
        }
    }
};

module.exports = checkToken;
